import { useEffect, useState } from 'react';

import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import { type FormInstance } from 'antd';

import ParamModal from './ParamModal';

/**
 * 参数项接口
 */
interface ParamItem {
  id?: string;
  name: string; // 参数名称
  identifier: string; // 标识符
  dataType: string; // 数据类型
  // 数据类型相关字段
  domains?: any[];
  boolT?: string;
  boolF?: string;
  dataLen?: string;
  dataLenUnit?: string;
  arrayDataType?: string;
  len?: string;
  min?: string;
  max?: string;
  step?: string;
  unit?: string;
  dateFormat?: string;
}

/**
 * 参数列表组件属性
 */
interface ParamListComponentProps {
  form: FormInstance;
  title?: string;
  fieldName?: string; // 字段名，默认为 'paramList'
  readonly?: boolean; // 是否只读模式
  value?: ParamItem[];
  onChange?: (value: ParamItem[]) => void;
}

/**
 * 参数列表组件
 */
const ParamListComponent = ({
  form,
  title = '输出参数(最多支持50个参数)',
  fieldName = 'paramList',
  readonly: _readonly = false,
  value = [],
  onChange,
}: ParamListComponentProps) => {
  const [paramList, setParamList] = useState<ParamItem[]>(value);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingParam, setEditingParam] = useState<ParamItem | null>(null);
  const [editingIndex, setEditingIndex] = useState<number>(-1);

  // 初始化时从表单中获取数据
  useEffect(() => {
    const formValue = form.getFieldValue(fieldName);
    if (formValue && Array.isArray(formValue) && formValue.length > 0) {
      setParamList(formValue);
    }
  }, [form, fieldName]);

  // 同步参数列表到表单
  const syncParamListToForm = (newList: ParamItem[]) => {
    setParamList(newList);
    onChange?.(newList);
    form.setFieldValue(fieldName, newList);
  };

  // 添加参数
  const handleAddParam = () => {
    setEditingParam(null);
    setEditingIndex(-1);
    setModalVisible(true);
  };

  // 编辑参数
  const handleEditParam = (param: ParamItem, index: number) => {
    setEditingParam(param);
    setEditingIndex(index);
    setModalVisible(true);
  };

  // 删除参数
  const handleDeleteParam = (index: number) => {
    const newList = paramList.filter((_, i) => i !== index);
    syncParamListToForm(newList);
  };

  // 保存参数
  const handleSaveParam = (paramData: ParamItem) => {
    let newList: ParamItem[];

    if (editingIndex >= 0) {
      // 编辑模式
      newList = [...paramList];
      newList[editingIndex] = { ...paramData, id: paramList[editingIndex].id };
    } else {
      // 添加模式
      newList = [...paramList, { ...paramData, id: Date.now().toString() }];
    }

    syncParamListToForm(newList);
    setModalVisible(false);
    setEditingParam(null);
    setEditingIndex(-1);
  };

  // 取消操作
  const handleCancel = () => {
    setModalVisible(false);
    setEditingParam(null);
    setEditingIndex(-1);
  };

  return (
    <>
      {/* 隐藏的字段，用于接收参数列表数据 */}
      <AForm.Item name={fieldName} hidden>
        <AInput />
      </AForm.Item>

      <ACol span={24}>
        <div style={{ marginBottom: 16 }}>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              marginBottom: 8,
            }}
          >
            <span style={{ fontWeight: 'bold' }}>{title}</span>
            <AButton
              type="dashed"
              icon={<PlusOutlined />}
              onClick={handleAddParam}
              disabled={paramList.length >= 50}
            >
              添加参数
            </AButton>
          </div>

          {paramList.length === 0 ? (
            <div
              style={{
                border: '1px dashed #d9d9d9',
                borderRadius: 6,
                padding: 40,
                textAlign: 'center',
                color: '#999',
              }}
            >
              暂无参数，点击"添加参数"开始添加
            </div>
          ) : (
            <div style={{ border: '1px solid #d9d9d9', borderRadius: 6 }}>
              {/* 表头 */}
              <div
                style={{
                  display: 'flex',
                  backgroundColor: '#fafafa',
                  padding: '12px 16px',
                  borderBottom: '1px solid #d9d9d9',
                  fontWeight: 'bold',
                }}
              >
                <div style={{ flex: 1 }}>参数名称</div>
                <div style={{ flex: 1 }}>标识符</div>
                <div style={{ flex: 1 }}>数据类型</div>
                <div style={{ width: 100, textAlign: 'center' }}>操作</div>
              </div>

              {/* 参数列表 */}
              {paramList.map((param, index) => (
                <div
                  key={param.id || index}
                  style={{
                    display: 'flex',
                    padding: '12px 16px',
                    borderBottom: index < paramList.length - 1 ? '1px solid #f0f0f0' : 'none',
                    alignItems: 'center',
                  }}
                >
                  <div style={{ flex: 1, color: '#333' }}>{param.name}</div>
                  <div style={{ flex: 1, color: '#666' }}>{param.identifier}</div>
                  <div style={{ flex: 1, color: '#666' }}>{param.dataType}</div>
                  <div style={{ width: 120, textAlign: 'center' }}>
                    <AButton
                      type="text"
                      size="small"
                      icon={<EditOutlined />}
                      onClick={() => handleEditParam(param, index)}
                      className="color-primary"
                      style={{ marginRight: 4 }}
                    >
                      编辑
                    </AButton>
                    <AButton
                      type="text"
                      size="small"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => handleDeleteParam(index)}
                    >
                      删除
                    </AButton>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </ACol>

      {/* 参数编辑Modal */}
      <ParamModal
        visible={modalVisible}
        editingParam={editingParam}
        onSave={handleSaveParam}
        onCancel={handleCancel}
      />
    </>
  );
};

export default ParamListComponent;
